package com.design.single;

/**
 * @author leal
 * @title: LazySingleton
 * @projectName DesignMode
 * @description: 懒汉式单例模式
 * @date 2021/7/21 21:06
 */
public class LazySingleton {
    private static volatile LazySingleton instance = null;

    /**
     * 直接使用synchronized修饰方法
     *
     * @return instance
     */
    synchronized public static LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }

    /**
     * 使用synchronized关键字修饰new 关键代码
     *
     * @return instance
     */
    public static LazySingleton getInstance2() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                instance = new LazySingleton();
            }
        }
        return instance;
    }

    /**
     * Double-Check Locking
     *
     * @return
     */
    public static LazySingleton getInstance3() {
        if (instance == null) {
            //第一重判断 锁定代码块
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    //第二重判断 创建单例模式
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }

    /**
     * IoDH技术
     * 增加一个静态内部类
     */
    private static class HolderClass {
        public static final LazySingleton instance = new LazySingleton();

    }

    public static LazySingleton getInstance4() {
        return HolderClass.instance;
    }
}
